<!DOCTYPE html>
<html lang="en">

<head>
    <title>机场区域查看编辑</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <script src="./utils/fengmap.map-license.min.js"></script>
    <script src="./utils/fengmap.plugin.draw.min.js"></script>
    <script src="./utils/fengmap.plugin.ui.min.js"></script>
    <script src="./utils/fengmap.plugin.fusion.min.js"></script>
    <script src="./utils/jquery-3.6.1.min.js"></script>
    <link rel="stylesheet" href="./css/layui.css">
    <link rel="stylesheet" href="./css/index.css">
    <link rel="stylesheet" href="./css/iconfont.css">
    <link rel="stylesheet" href="./css/toolBarStyle.css" />
    <link rel="stylesheet" href="./css/mapEditorNew.css">
    <style>
        .toolBarDiv {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .fm-control-groups {
            right: 20px !important;
        }

        .top-right {
            margin-right: 20px;
        }
    </style>
</head>

<body>
    <div class="toolBarDiv">
        <div class="control1">
            <!-- <button id="addPoint" type="button" class="layui-btn" onclick="drawOpetion('addPoint')">
                <i class="iconfont icon-dian"></i>
            </button>
            <button id="addLine" type="button" class="layui-btn" onclick="drawOpetion('addLine')">
                <i class="iconfont icon-xian"></i>
            </button> -->
            <div class="dropdown">
                <button id="mian" type="button" class="layui-btn" onclick="drawOpetion('dbx')">
                    <i id="dbx" class="iconfont icon-juxing"></i>
                </button>
                <div id="control2" class="control1">
                    <button id="addRectangle" type="button" class="layui-btn"
                        onclick="drawOpetion('addRectangle', 'icon-juxing')">
                        <i class="iconfont icon-juxing"></i>
                    </button>
                    <button id="addPolygon" type="button" class="layui-btn"
                        onclick="drawOpetion('addPolygon', 'icon-duobianxing')">
                        <i class="iconfont icon-duobianxing"></i>
                    </button>
                    <button id="addCircle" type="button" class="layui-btn"
                        onclick="drawOpetion('addCircle', 'icon-yuan')">
                        <i class="iconfont icon-yuan"></i>
                    </button>
                    <button id="addEllipse" type="button" class="layui-btn"
                        onclick="drawOpetion('addEllipse', 'icon-tuoyuan')">
                        <i class="iconfont icon-tuoyuan"></i>
                    </button>
                </div>
            </div>
            <button id="edit" type="button" class="layui-btn" onclick="drawOpetion('edit')">
                <i class="iconfont icon-huizhi"></i>
            </button>
            <button id="delete" type="button" class="layui-btn layui-btn-disabled" onclick="drawOpetion('delete')">
                <i class="iconfont icon-shanchu"></i>
            </button>
        </div>

        <div class="top-right">
            <button id="delete" type="button" class="layui-btn" onclick="redraw()">
                刷新
            </button>
            <!-- <button id="delete" type="button" class="layui-btn layui-btn-primary" onclick="save()">
                保存新增
            </button> -->
        </div>
    </div>
    <!-- <div class="tip">
        <p>
            <img src="https://developer.fengmap.com/fmAPI/images/tip.png" />请选择左侧工具绘制marker或对已有marker进行选中、移动、修改形状、删除等的编辑。
        </p>
        <p style="margin-left: 23px;">编辑状态下点击边线上的虚拟中点“小白点”可增加节点；选中任一节点点击“删除”图标可删除选中的节点。</p>
        <p style="margin-left: 23px;">注：虚拟中点无法删除。</p>
    </div> -->
    <div id="fengmap"></div>
</body>
<script>
    var $parent_this;
    var currentHandlePolygon = null;
    var polygonAreas = [];
    var polygonOptions = [];
    var finallyDrawData = null;

    var map;
    var mapdraw; // 绘制类
    var activeBtn; // 当前选中btn
    var markerList;
    var dbx = 'addRectangle';
    var dbxicon = 'icon-juxing';
    var subs = ['addRectangle', 'addPolygon', 'addCircle', 'addEllipse']; // 子菜单
    var historyAreaLevel = sessionStorage.getItem("O2O_AreaLevel") || 6;
    var options = {
        container: document.getElementById('fengmap'),
        appName: "商场导览端样例的导览端微程序",
        key: "36344769ec20478ffa7944380d45b217",
        mapID: '1813117783302119425',
        themeID: '1813128535299932162',
        license: "17a8f3db01aa030bf4f496d6d828c898",
        center: {
            x: 13559440.116626736,
            y: 3650453.950961055
        },
        level: parseInt(historyAreaLevel),
        mapZoom: 16,
        zoomRange: [10, 23],
        highlightPicker: [],                    // 取消触发高亮事件
        viewMode: fengmap.FMViewMode.MODE_2D,   // 2D视图模式
    }
    map = new fengmap.FMMap(options);
    map.on('loaded', function () {
        console.log('地图加载完成');
        initMapTapEvent();
        initFloorControl()
        // 初始化点线面编辑类
        initMapEditor();
        backView();
    })
    map.on('levelChanged', function (e) {
        sessionStorage.setItem("O2O_AreaLevel", e.level)
    })
    /* 点击事件监听 */
    // map.on('click', function (e) {
    //     // 拾取当前选中marker
    //     console.log(e);
    //     markerList = e.targets[0]

    // });


    let debounceTimer = null;
    function debounce(callback, duration = 500) {
        return function (...args) {
            let ctx = this;
            if (debounceTimer) clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                callback.apply(ctx, args);
            }, duration);
        };
    };

    // //键盘事件
    // document.onkeydown = function (e) {
    //     //判断mac系统还是windows系统  点击键盘delete健 删除节点或图形
    //     if (e.code === "Backspace") {
    //         if (activeBtn === "edit") {
    //             mapdraw.delete(markerList)
    //             markerList = null
    //         }
    //     }
    //     if (e.code === "Delete ") {
    //         if (activeBtn === "edit") {
    //             mapdraw.delete(markerList)
    //             markerList = null
    //         }
    //     }
    // }

    function latlngToMapXyCoords({ lat, lng }) {
        let mapCoords = fengmap.FMCalculator.latlngToMapCoordinate({
            x: Number(lng),
            y: Number(lat),
        });
        return mapCoords;
    }

    function mapXyToLatlngCoords({ x, y }) {
        let { x: lng, y: lat } = fengmap.FMCalculator.mapCoordinateToLatlng({
            x,
            y,
        });
        return {
            lng,
            lat,
        };
    }
    function initMapTapEvent() {
        map.on("click", function (e) {
            // e = {
            //     ...e,
            //     location: mapXyToLatlngCoords({
            //         ...e.coords,
            //     }),
            // };
            // console.log(
            //     e,
            //     "    ",
            //     // JSON.stringify({ x: e.coords.x, y: e.coords.y })
            //     JSON.stringify(e.location)
            // );
        });
    }
    // 初始化楼层导航器
    function initFloorControl() {
        floorInfos = map.getFloorInfos();
        var scrollFloorCtlOpt = {
            position: fengmap.FMControlPosition.RIGHT_TOP,
            floorButtonCount: 5,
            offset: {
                // x: -630,
                // y: 400
            },
            viewModeControl: true,
            floorModeControl: true,
            needAllLayerBtn: true,
        };
        scrollFloorControl = new fengmap.FMToolbar(scrollFloorCtlOpt);
        scrollFloorControl.addTo(map);
    }

    function handleData(event, type = 'edit') {
        if (currentHandlePolygon && currentHandlePolygon._type == 'delete') {
            clearRecordData();
            return
        }
        clearRecordData();
        let parent = polygonAreas.find(f => event.target.userID == f.userID);
        console.log("parent", parent);
        if (type == 'edit' && !parent) return;
        if (type == 'edit') {
            currentHandlePolygon = {
                ...parent,
                floor: map.getFloor(map.getLevel()).name,
                _type: 'edit'
            };
        } else {
            currentHandlePolygon = {
                id: "",
                airportStation: [],
                floor: map.getFloor(map.getLevel()).name,
                _type: 'add'
            }
        }
        $parent_this.selectedArea = currentHandlePolygon;
        let list = event.target.points.map(p => {
            let latLng = mapXyToLatlngCoords(p)
            p = {
                level: map.getLevel(),
                floor: map.getFloor(map.getLevel()).name,
                points: {
                    ...p,
                    ...latLng
                }
            }
            return p
        });
        let res = lastData(list)
        finallyDrawData = res;
        console.log(event.type == "drawn" ? '绘制完成--->' : event.type == "edited" ? '编辑完成--->' : '', currentHandlePolygon, "<<<>>>", finallyDrawData);
        save();
    }

    /* 初始化点线面编辑类 */
    function initMapEditor() {
        mapdraw = new fengmap.FMMarkerEditor(map);
        //设置点样式
        mapdraw.setStyle("pointStyle", {
            url: "https://developer.fengmap.com/fmAPI/images/edit-point.png", //图片url地址
            size: 32, //大小
            height: 3, //高度
            collision: false,
            anchor: fengmap.FMMarkerAnchor.CENTER
        });
        //设置线样式
        mapdraw.setStyle("lineStyle", {
            width: 2, //线的宽度
            type: fengmap.FMLineType.FULL, //线的类型
            color: '#2F79EE', //颜色
            height: 3 //高度
        });
        //设置面样式
        mapdraw.setStyle("polygonStyle", {
            color: '#8DB9FF', //颜色
            borderWidth: 2, //外框的宽度
            borderColor: '#2F79EE', //外框的颜色
            opacity: 0.5, //透明度
            height: 3 //高度
        });

        mapdraw.setStyle("centerStyle", { url: "https://developer.fengmap.com/fmAPI/images/edit-center.png", size: 20 });//设置中心标识图片地址
        mapdraw.setStyle("nodeStyle", {
            editStyle: {
                url: "https://developer.fengmap.com/fmAPI/images/pic-03.png",
                size: 12
            },
            newStyle: {
                url: "https://developer.fengmap.com/fmAPI/images/edit-node.png",
                size: 8,
            },
            selectedStyle: {
                url: "https://developer.fengmap.com/fmAPI/images/pic-03.png",
                size: 16,
            }
        })
        // mapdraw.setStyle("editStyle", { url: "https://developer.fengmap.com/fmAPI/images/edit-node.png", size: 10 });//设置顶点标识图片地址
        mapdraw.setStyle("pointRectColor", "#2F79EE");//设置点外包围框的颜色

        mapdraw.enable();//启用编辑工具
        // 绘制完成事件监听
        mapdraw.on("drawing", function (event) {
            console.log(event);
        });
        mapdraw.on("drawn", function (event) {
            console.log(event);
            console.log("finallyDrawData", finallyDrawData);
            console.log("currentHandlePolygon", currentHandlePolygon);
            if (!finallyDrawData && !currentHandlePolygon) {
                handleData(event, "add")
            }
        });
        mapdraw.on("deleted", function (event) {
            console.log("deleted", event);
            removeArea(event);
        });
        mapdraw.on("edited", function (event) {
            console.log("edited", event);
            finallyDrawData = null;
            handleData(event)
        });
        mapdraw.on("deleteNode", function (event) {
            console.log(event);
        });
    }

    function removeArea(event) {
        let delArea = polygonAreas.find(f => f.userID == event.target.userID)
        console.log(delArea);
        if (delArea) {
            $parent_this.$http({
                url: $parent_this.$http.adornUrl(`/platform/shopDetail/poi/deleteStationRestrict/${delArea.id}`),
                method: "post",
            }).then(result => {
                if (result.code == "00000") {
                    $parent_this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                }
            })
        }

    }

    function lastData(arr) {
        let list = arr.map(m => {
            return {
                ...m.points,
                level: m.level,
                floor: map.getFloor(m.level).name,
            }
        })
        return list
    }

    function redraw() {
        location.reload();
    }
    function save() {
        if (!finallyDrawData || !currentHandlePolygon) {
            $parent_this.$message({
                message: '没有检测到编辑记录',
                type: 'warning'
            });
            return;
        }
        if (currentHandlePolygon._type == 'add') {
            let timer;
            timer = setTimeout(() => {
                $parent_this.addAreaVisible = true;
                clearTimeout(timer)
            }, 200);
            return
        }
        this.confirmSaveDraw()
    }
    function confirmSaveDraw() {
        let p = {
            id: currentHandlePolygon.id,
            airportStation: JSON.stringify(currentHandlePolygon.airportStation),
            pointRestrict: JSON.stringify(finallyDrawData),
            floor: currentHandlePolygon.floor,
        }
        console.log(">>>>>>", p);
        $parent_this.$http({
            url: $parent_this.$http.adornUrl(currentHandlePolygon._type == 'add' ? "/platform/shopDetail/poi/addStationRestrict" : "/platform/shopDetail/poi/updateStationRestrict"),
            method: "post",
            data: p
        }).then(result => {
            if (result.code == "00000") {
                $parent_this.$message({
                    message: '保存成功',
                    type: 'success'
                });
                if (currentHandlePolygon._type == 'add') {
                    redraw();
                }
            }
        })
    }
    function clearRecordData() {
        $parent_this.selectedArea = {};
        currentHandlePolygon = null;
        finallyDrawData = null;
    }
    /* 设置绘制类型 */
    function drawOpetion(type, icon) {
        // 清空选中
        if (activeBtn) {
            var activeDom = document.getElementById(activeBtn);
            activeDom.classList.remove('active');
            if (subs.indexOf(activeBtn) > -1) {
                var dom = document.getElementById('mian');
                dom.classList.remove('active');
            }
        }
        //再次点击取消
        if (type === activeBtn && type !== 'delete') {
            mapdraw.operationType = null;
            return;
        }
        if (type === 'dbx') {
            type = dbx;
            icon = dbxicon;
        };

        if (type === 'delete') {
            currentHandlePolygon = {
                _type: 'delete'
            }
            $parent_this.$confirm('此操作将删除该区域, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                mapdraw.delete(markerList)
            })
        } else {
            // 设置类型
            mapdraw.operationType = type;
        }
        if (mapdraw.operationType === 'edit') {
            $('#delete').removeAttr('disabled')
            $('#delete').removeClass('layui-btn-disabled');
            var dom = document.getElementById("edit");
            dom.classList.add('active');
        } else {
            $('#delete').attr('disabled', true)
            $('#delete').addClass('layui-btn-disabled');
            var dom = document.getElementById("edit");
            dom.classList.remove('active');
        }

        //更新选中
        if (subs.indexOf(type) > -1) {
            var dom1 = document.getElementById('dbx');
            dom1.classList.remove(dbxicon);
            dbx = type;
            dbxicon = icon;
            var dom = document.getElementById('mian');
            dom.classList.add('active');
            dom1.classList.add(dbxicon);
            clearRecordData();
        }
        if (type != "delete") {
            var dom = document.getElementById(type);
            dom.classList.add('active');
        }
        activeBtn = type;
    }

    function backView() {
        $parent_this.$http.get($parent_this.$http.adornUrl("/platform/shopDetail/poi/airportStationRestrictList"))
            .then(result => {
                polygonAreas = result.data.map(m => {
                    let pointRestrict = isJsonString(m.pointRestrict) ? JSON.parse(m.pointRestrict) : [];
                    m.airportStation = isJsonString(m.airportStation) ? JSON.parse(m.airportStation) : m.airportStation;
                    pointRestrict.forEach(f => {
                        f.parent = { airportStation: m.airportStation, floor: m.floor, id: m.id };
                    });
                    return { ...m, pointRestrict };
                });
                polygonAreas.forEach(f => {
                    let polygonOption = {
                        markerType: fengmap.FMType.POLYGON_MARKER,
                        points: f.pointRestrict,
                        level: f.pointRestrict[0]?.level,
                    };
                    mapdraw.add(polygonOption);
                    let mmkItem = mapdraw.markers.find(ff => ff.points[0].parent.id === f.id);
                    f.userID = mmkItem?.userID;
                });
                console.log("polygonAreas, $parent_this", polygonAreas, $parent_this);
                $('#delete').attr('disabled', true);
            });
    }
    function isJsonString(str) {
        try {
            if (typeof JSON.parse(str) == "object") {
                return true;
            }
        } catch (e) {
        }
        return false;
    }

</script>

</html>